<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px; margin: auto"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="项目类型" prop="itemStatus">
      <el-select v-model="ruleForm.itemStatus" placeholder="请选择">
        <el-option
          v-for="item in typeList"
          :value="item.id"
          :key="item.id"
          :label="item.name"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="用户名" prop="itemUsername">
      <el-input v-model="ruleForm.itemUsername" />
    </el-form-item>
    <el-form-item label="借贷人姓名" prop="getName">
      <el-input v-model="ruleForm.getName" />
    </el-form-item>
    <el-form-item label="项目名称" prop="xmName">
      <el-input v-model="ruleForm.xmName" />
    </el-form-item>
    <el-form-item label="借贷款金额" prop="getPrice">
      <el-input v-model="ruleForm.getPrice" />
    </el-form-item>
    <el-form-item label="借款期限" prop="qx">
      <el-input v-model="ruleForm.qx" />
    </el-form-item>

    <el-form-item label="添加时间" prop="addTime">
      <el-date-picker
        v-model="ruleForm.addTime"
        type="datetime"
        aria-label="请输入"
        placeholder="请输入"
        value-format="YYYY-MM-DD HH:mm:ss"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="相关图片" prop="region">
      <el-upload
        v-model:file-list="fileList"
        action="http://localhost:10010/user/item/imageUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :headers="headers"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { loginFrom, listType, addItemList } from "../api/api";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";

const fileList = ref<UploadUserFile[]>([]);

const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<any>({
  addTime: "",
  getName: "",
  getPrice: null,
  id: null,
  itemStatus: null,
  itemUsername: "",
  lx: "",
  prodImageLists: [],
  qx: "",
  xmName: "",
  xmType: "",
});

const headers = ref({
  token: sessionStorage.getItem("token"),
});

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<any>>({
  itemStatus: [
    { required: true, message: "项目类型必须填写", trigger: "blur" },
  ],
  itemUsername: [
    { required: true, message: "用户名必须填写", trigger: "blur" },
  ],
  getName: [{ required: true, message: "借贷人姓名必须填写", trigger: "blur" }],
  xmName: [{ required: true, message: "项目名称必须填写", trigger: "blur" }],
  getPrice: [{ required: true, message: "借贷款必须填写", trigger: "blur" }],
  qx: [{ required: true, message: "借贷期限必须填写", trigger: "blur" }],
  addTime: [{ required: true, message: "添加时间必须填写", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("fileList", fileList.value);
      fileList.value.forEach((item: any) => {
        let img = {
          imageUrl: item.response.data,
        };
        ruleForm.value.prodImageLists.push(img);
      });

      addItemList(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          router.push("/ItemList");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
const typeList = ref([]);
// 页面加载钩子函数
onMounted(() => {
  let u = sessionStorage.getItem("user");
  //   console.log(u);
  if (u != null) {
    let user = JSON.parse(u);
    console.log(user);
    ruleForm.value.itemUsername = user.phone;
  }

  listType("").then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
});
</script>
